const db = require("../common/db");
class SearchPhotos {
  // 上传图片
  imgs(name, imgUrls) {
    return new Promise((resolve, reject) => {
      if (!Array.isArray(imgUrls) || imgUrls.length === 0) {
        return reject({
          code: -1,
          msg: "请提供有效的图片链接",
        });
      }

      const imgUrlString = imgUrls.join("\n"); // 将数组转换为字符串

      // 查询是否存在相同 name 的记录
      db.query(`SELECT imgurl FROM photocategory WHERE name='${name}'`)
        .then((rows) => {
          if (rows.length > 0) {
            // 如果存在，合并新图片链接
            const existingPhotos = rows[0].imgurl
              ? rows[0].imgurl.split("\n")
              : []; // 读取现有的图片链接并转为数组

            // 合并新旧图片链接并去重
            const allPhotosSet = new Set([...existingPhotos, ...imgUrls]);
            const updatedPhotos = Array.from(allPhotosSet).join("\n"); // 转回字符串

            // 更新现有记录，追加新图片链接
            return db.query(
              `UPDATE photocategory SET imgurl='${updatedPhotos}' WHERE name='${name}'`
            );
          } else {
            // 插入新记录
            return db.query(
              `INSERT INTO photocategory(name, imgurl) VALUES ('${name}', '${imgUrlString}')`
            );
          }
        })
        .then(() => {
          resolve({
            code: 200,
            msg: `操作成功`,
            status: "正常",
          });
        })
        .catch((error) => {
          console.error("发生错误:", error);
          reject({
            code: -1,
            msg: "服务端发生错误",
            error: error.message || error,
          });
        });
    });
  }

  // 查询图片
  imgs_list() {
    return new Promise((resolve, reject) => {
      db.query(`select  *  from photocategory`).then(
        (row) => {
          resolve({
            code: 200,
            msg: "获取图片成功",
            result: row,
          });
        },
        (error) => {
          reject({
            code: -1,
            msg: "获取图片失败",
            error,
          });
        }
      );
    });
  }

  // 删除整条记录
  removedata(name) {
    return new Promise((resolve, reject) => {
      // 根据text字段查询是否存在重复的名称
      db.query(`select name from photocategory where name = '${name}'`).then(
        (row) => {
          if (row.length == 0) {
            resolve({
              code: 404,
              msg: `这个“${name}”不存在`,
            });
          } else {
            // 执行删除操作
            db.query(`delete from photocategory where name = '${name}'`)
              .then((content) => {
                resolve({
                  code: 200,
                  msg: `删除该“${name}”分类名称成功`,
                  status: content.changedRows === 0 ? "正常" : "异常",
                });
              })
              .catch((error) => {
                reject({
                  code: -1,
                  msg: `删除该“${name}”分类名称失败`,
                  error,
                });
              });
          }
        }
      );
    });
  }
}
module.exports = SearchPhotos;
